<template>
  <div class="user-data-management-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <i class="iconify" data-icon="mdi:database-settings"></i>
        用户数据管理
      </h1>
      <div class="page-actions">
        <button class="btn btn-outline" @click="exportUserData">
          <i class="iconify" data-icon="mdi:download"></i>
          导出数据
        </button>
        <button class="btn btn-warning" @click="showImportUserDialog">
          <i class="iconify" data-icon="mdi:upload"></i>
          导入用户
        </button>

        <button class="btn btn-success" @click="showAddUserDialog">
          <i class="iconify" data-icon="mdi:account-plus"></i>
          添加用户
        </button>
        <button class="btn btn-primary" @click="refreshData">
          <i class="iconify" data-icon="mdi:refresh"></i>
          刷新数据
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">总用户数</div>
            <div class="stat-value">{{ userStats.totalUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <i class="iconify" data-icon="mdi:trending-up"></i>
                {{ userStats.totalUsersGrowth }}%
              </span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-blue">
            <i class="iconify" data-icon="mdi:account-group"></i>
          </div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">活跃用户</div>
            <div class="stat-value">{{ userStats.activeUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <i class="iconify" data-icon="mdi:trending-up"></i>
                {{ userStats.activeUsersGrowth }}%
              </span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-green">
            <i class="iconify" data-icon="mdi:account-check"></i>
          </div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">VIP用户</div>
            <div class="stat-value">{{ userStats.vipUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <i class="iconify" data-icon="mdi:trending-up"></i>
                {{ userStats.vipUsersGrowth }}%
              </span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-orange">
            <i class="iconify" data-icon="mdi:crown"></i>
          </div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">今日新增</div>
            <div class="stat-value">{{ userStats.newUsersToday }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <i class="iconify" data-icon="mdi:trending-up"></i>
                {{ userStats.newUsersTodayGrowth }}%
              </span>
              <span class="trend-label">较昨天</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-purple">
            <i class="iconify" data-icon="mdi:account-plus"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <!-- 筛选条件、搜索、操作一行布局 -->
      <div class="filter-row-unified">
        <!-- 筛选条件组 -->
        <div class="filter-group">
          <label>账号状态</label>
          <select v-model="filters.status" class="filter-select" @change="applyFilters">
            <option value="">全部状态</option>
            <option value="active">正常</option>
            <option value="banned">封禁</option>
            <option value="suspended">暂停</option>
          </select>
        </div>
        <div class="filter-group">
          <label>VIP状态</label>
          <select v-model="filters.vipStatus" class="filter-select" @change="applyFilters">
            <option value="">全部</option>
            <option value="none">普通用户</option>
            <option value="monthly">月度VIP</option>
            <option value="yearly">年度VIP</option>
          </select>
        </div>
        <div class="filter-group">
          <label>用户角色</label>
          <select v-model="filters.role" class="filter-select" @change="applyFilters">
            <option value="">全部角色</option>
            <option value="user">普通用户</option>
            <option value="moderator">版主</option>
            <option value="admin">管理员</option>
          </select>
        </div>
        <div class="filter-group">
          <label>注册时间</label>
          <select v-model="filters.dateRange" class="filter-select" @change="applyFilters">
            <option value="">全部时间</option>
            <option value="today">今天</option>
            <option value="week">最近一周</option>
            <option value="month">最近一月</option>
            <option value="quarter">最近三月</option>
          </select>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-group">
          <label>搜索用户</label>
          <div class="search-wrapper">
            <input 
              v-model="searchQuery" 
              type="text" 
              placeholder="邮箱、昵称、ID"
              class="search-input"
              @keyup.enter="performSearch"
            >
            <button class="search-btn" @click="performSearch" :disabled="loading">
              <i class="iconify" data-icon="mdi:magnify"></i>
            </button>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="filter-actions">
          <button class="btn btn-outline btn-sm" @click="resetFilters">
            <i class="iconify" data-icon="mdi:filter-remove"></i>
            重置
          </button>
          <button 
            v-if="selectedUsers.length > 0"
            class="btn btn-warning btn-sm" 
            @click="showBatchActionDialog"
          >
            <i class="iconify" data-icon="mdi:account-multiple"></i>
            批量 ({{ selectedUsers.length }})
          </button>
        </div>
      </div>
      
      <!-- 高级筛选条件（紧凑版） -->
      <div class="advanced-filters-compact">
        <div class="advanced-content-layout">
          <div class="advanced-filters-left">
            <div class="advanced-group-small">
              <label>余额范围</label>
              <div class="range-wrapper-small">
                <input 
                  v-model="advancedFilters.balanceMin" 
                  type="number" 
                  placeholder="最小"
                  class="range-input-small"
                  @input="loadUsers"
                >
                <span>-</span>
                <input 
                  v-model="advancedFilters.balanceMax" 
                  type="number" 
                  placeholder="最大"
                  class="range-input-small"
                  @input="loadUsers"
                >
              </div>
            </div>
            <div class="advanced-group-small">
              <label>注册日期</label>
              <div class="range-wrapper-small">
                <input 
                  v-model="advancedFilters.dateFrom" 
                  type="date"
                  class="date-input-small"
                  @change="loadUsers"
                >
                <span>至</span>
                <input 
                  v-model="advancedFilters.dateTo" 
                  type="date"
                  class="date-input-small"
                  @change="loadUsers"
                >
              </div>
            </div>
            <div class="advanced-group-small">
              <label>等级范围</label>
              <div class="range-wrapper-small">
                <input 
                  v-model="advancedFilters.levelMin" 
                  type="number" 
                  placeholder="最小"
                  class="range-input-small"
                  @input="loadUsers"
                >
                <span>-</span>
                <input 
                  v-model="advancedFilters.levelMax" 
                  type="number" 
                  placeholder="最大"
                  class="range-input-small"
                  @input="loadUsers"
                >
              </div>
            </div>
            <div class="advanced-group-small">
              <label>登录状态</label>
              <select v-model="advancedFilters.hasLoggedIn" class="filter-select-small" @change="loadUsers">
                <option value="">全部</option>
                <option value="true">已登录</option>
                <option value="false">未登录</option>
              </select>
            </div>
          </div>
          <div class="advanced-actions-right">
            <button class="btn btn-outline btn-sm" @click="clearAdvancedFilters">
              <i class="iconify" data-icon="mdi:close"></i>
              清空条件
            </button>
            <button class="btn btn-primary btn-sm" @click="loadUsers">
              <i class="iconify" data-icon="mdi:magnify"></i>
              应用搜索
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

    <!-- 用户数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>
              <input 
                type="checkbox" 
                @change="toggleSelectAll"
                :checked="isAllSelected"
                :indeterminate="isPartialSelected"
              >
            </th>
            <th>用户信息</th>
            <th>登录信息</th>
            <th>账号状态</th>
            <th>VIP状态</th>
            <th>钱包余额</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUsers" :key="user.id" class="table-row">
            <td>
              <input 
                type="checkbox" 
                :value="user.id"
                v-model="selectedUsers"
              >
            </td>
            <td>
              <div class="user-info">
                <div class="user-avatar">
                  <img :src="user.avatar || '/default-avatar.svg'" :alt="user.nickname" @error="handleImageError">
                </div>
                <div class="user-details">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-email">{{ user.email }}</div>
                  <div class="user-id">ID: {{ user.id }}</div>
                  <div class="user-role">{{ getRoleText(user.role || 'user') }}</div>
                </div>
              </div>
            </td>
            <td>
              <div class="login-info">
                <div class="last-login">
                  <strong>最后登录:</strong><br>
                  {{ user.lastLoginTime ? formatDateTime(user.lastLoginTime) : '从未登录' }}
                </div>
                <div class="register-ip" v-if="user.registerIp">
                  <strong>注册IP:</strong> {{ user.registerIp }}
                </div>
              </div>
            </td>
            <td>
              <div class="status-cell">
                <select 
                  :value="user.status" 
                  @change="handleStatusChange(user, $event)"
                  class="status-select"
                  :class="user.status"
                >
                  <option value="active">正常</option>
                  <option value="banned">封禁</option>
                  <option value="suspended">暂停</option>
                </select>
                <div v-if="user.banReason" class="ban-reason">
                  原因: {{ user.banReason }}
                </div>
                <div v-if="user.banExpireDate" class="ban-expire">
                  到期: {{ formatDate(user.banExpireDate) }}
                </div>
              </div>
            </td>
            <td>
              <div class="vip-status">
                <span v-if="user.vipStatus !== 'none'" class="vip-badge">
                  <i class="iconify" data-icon="mdi:crown"></i>
                  {{ getVipText(user.vipStatus || 'none') }}
                </span>
                <span v-else class="normal-user">普通用户</span>
                <div v-if="user.vipExpireDate && user.vipStatus !== 'none'" class="vip-expire">
                  到期: {{ formatDate(user.vipExpireDate) }}
                </div>
              </div>
            </td>
            <td>
              <div class="wallet-info">
                <div class="balance-amount">{{ getBalanceAmount(user) }} 书币</div>
                <div class="recharge-info">
                  <small>充值: {{ (user.totalRecharge || 0).toLocaleString() }}</small><br>
                  <small>消费: {{ (user.totalConsumption || 0).toLocaleString() }}</small>
                </div>
              </div>
            </td>
            <td>
              <div class="date-info">
                <div>{{ formatDate(user.createdAt) }}</div>
                <small>{{ formatTime(user.createdAt) }}</small>
              </div>
            </td>
            <td>
              <div class="action-buttons">
                <div class="action-row">
                  <button 
                    class="action-btn detail" 
                    @click="showUserDetailDialog(user)"
                    title="查看详情"
                  >
                    <i class="iconify" data-icon="mdi:account-details"></i>
                    <span>详情</span>
                  </button>
                  <button 
                    class="action-btn edit" 
                    @click="showEditUserDialog(user)"
                    title="编辑用户"
                  >
                    <i class="iconify" data-icon="mdi:pencil"></i>
                    <span>编辑</span>
                  </button>
                  <button 
                    class="action-btn password" 
                    @click="showResetPasswordDialog(user)"
                    title="重置密码"
                  >
                    <i class="iconify" data-icon="mdi:key"></i>
                    <span>密码</span>
                  </button>
                </div>
                <div class="action-row">
                  <button 
                    class="action-btn view" 
                    @click="viewUserPassword(user)"
                    title="查看密码"
                  >
                    <i class="iconify" data-icon="mdi:eye"></i>
                    <span>查看</span>
                  </button>
                  <button 
                    class="action-btn danger" 
                    @click="confirmDeleteUser(user)"
                    title="删除用户"
                    v-if="user.role !== 'admin'"
                  >
                    <i class="iconify" data-icon="mdi:delete"></i>
                    <span>删除</span>
                  </button>
                  <!-- 为管理员用户填充空白，保持布局一致 -->
                  <div v-if="user.role === 'admin'" class="btn-placeholder"></div>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页 -->
      <div class="pagination">
        <div class="pagination-info">
          显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, filteredUsers.length) }} 条，
          共 {{ filteredUsers.length }} 条
        </div>
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            @click="currentPage = 1" 
            :disabled="currentPage === 1"
          >
            首页
          </button>
          <button 
            class="page-btn" 
            @click="currentPage--" 
            :disabled="currentPage === 1"
          >
            上一页
          </button>
          <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <button 
            class="page-btn" 
            @click="currentPage++" 
            :disabled="currentPage === totalPages"
          >
            下一页
          </button>
          <button 
            class="page-btn" 
            @click="currentPage = totalPages" 
            :disabled="currentPage === totalPages"
          >
            末页
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <div v-if="showUserDialog" class="modal-overlay" @click="closeUserDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑用户' : '添加用户' }}</h3>
          <button class="close-btn" @click="closeUserDialog">
            <i class="iconify" data-icon="mdi:close"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-row">
              <div class="form-group">
                <label>邮箱 *</label>
                <input 
                  v-model="userForm.email" 
                  type="email" 
                  required 
                  :disabled="isEditing"
                  class="form-input"
                >
              </div>
              <div class="form-group">
                <label>昵称 *</label>
                <input 
                  v-model="userForm.nickname" 
                  type="text" 
                  required 
                  class="form-input"
                >
              </div>
            </div>
            <div class="form-row" v-if="!isEditing">
              <div class="form-group">
                <label>密码 *</label>
                <input 
                  v-model="userForm.password" 
                  type="password" 
                  required 
                  class="form-input"
                >
              </div>
              <div class="form-group">
                <label>确认密码 *</label>
                <input 
                  v-model="userForm.confirmPassword" 
                  type="password" 
                  required 
                  class="form-input"
                >
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>用户角色</label>
                <select v-model="userForm.role" class="form-select">
                  <option value="user">普通用户</option>
                  <option value="moderator">版主</option>
                  <option value="admin">管理员</option>
                </select>
              </div>
              <div class="form-group">
                <label>账号状态</label>
                <select v-model="userForm.status" class="form-select">
                  <option value="active">正常</option>
                  <option value="banned">封禁</option>
                  <option value="suspended">暂停</option>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>VIP状态</label>
                <select v-model="userForm.vipStatus" class="form-select">
                  <option value="none">普通用户</option>
                  <option value="monthly">月度VIP</option>
                  <option value="yearly">年度VIP</option>
                </select>
              </div>
              <div class="form-group">
                <label>用户等级</label>
                <input 
                  v-model.number="userForm.level" 
                  type="number" 
                  min="1" 
                  max="100"
                  class="form-input"
                >
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>钱包余额 (书币)</label>
                <input 
                  v-model.number="userForm.balance" 
                  type="number" 
                  min="0"
                  class="form-input"
                >
              </div>
              <div class="form-group">
                <label>头像URL</label>
                <input 
                  v-model="userForm.avatar" 
                  type="url"
                  class="form-input"
                  placeholder="http://example.com/avatar.jpg"
                >
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeUserDialog">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ isEditing ? '保存修改' : '添加用户' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <div v-if="showDetailDialog" class="modal-overlay" @click="closeDetailDialog">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>用户详情 - {{ selectedUser?.nickname }}</h3>
          <button class="close-btn" @click="closeDetailDialog">
            <i class="iconify" data-icon="mdi:close"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="user-detail-grid" v-if="selectedUser">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <span class="label">用户ID:</span>
                <span class="value">{{ selectedUser.id }}</span>
              </div>
              <div class="detail-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ selectedUser.email }}</span>
              </div>
              <div class="detail-item">
                <span class="label">昵称:</span>
                <span class="value">{{ selectedUser.nickname }}</span>
              </div>
              <div class="detail-item">
                <span class="label">用户等级:</span>
                <span class="value">Lv.{{ selectedUser.level }}</span>
              </div>
              <div class="detail-item">
                <span class="label">用户角色:</span>
                <span class="value">{{ getRoleText(selectedUser.role || 'user') }}</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>账号状态</h4>
              <div class="detail-item">
                <span class="label">状态:</span>
                <span class="value" :class="selectedUser.status">{{ getStatusText(selectedUser.status || 'active') }}</span>
              </div>
              <div class="detail-item" v-if="selectedUser.banReason">
                <span class="label">封禁原因:</span>
                <span class="value">{{ selectedUser.banReason }}</span>
              </div>
              <div class="detail-item" v-if="selectedUser.banExpireDate">
                <span class="label">封禁到期:</span>
                <span class="value">{{ formatDateTime(selectedUser.banExpireDate) }}</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>VIP信息</h4>
              <div class="detail-item">
                <span class="label">VIP状态:</span>
                <span class="value">{{ getVipText(selectedUser.vipStatus || 'none') }}</span>
              </div>
              <div class="detail-item" v-if="selectedUser.vipExpireDate && selectedUser.vipStatus !== 'none'">
                <span class="label">VIP到期:</span>
                <span class="value">{{ formatDateTime(selectedUser.vipExpireDate) }}</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>钱包信息</h4>
              <div class="detail-item">
                <span class="label">当前余额:</span>
                <span class="value">{{ getBalanceAmount(selectedUser) }} 书币</span>
              </div>
              <div class="detail-item">
                <span class="label">累计充值:</span>
                <span class="value">{{ (selectedUser.totalRecharge || 0).toLocaleString() }} 书币</span>
              </div>
              <div class="detail-item">
                <span class="label">累计消费:</span>
                <span class="value">{{ (selectedUser.totalConsumption || 0).toLocaleString() }} 书币</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>阅读统计</h4>
              <div class="detail-item">
                <span class="label">阅读时长:</span>
                <span class="value">{{ Math.round((selectedUser.readingTime || 0) / 60) }} 分钟</span>
              </div>
              <div class="detail-item">
                <span class="label">已读书籍:</span>
                <span class="value">{{ selectedUser.booksRead || 0 }} 本</span>
              </div>
              <div class="detail-item">
                <span class="label">购买章节:</span>
                <span class="value">{{ (selectedUser.purchasedChapters || []).length }} 章</span>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>时间信息</h4>
              <div class="detail-item">
                <span class="label">注册时间:</span>
                <span class="value">{{ formatDateTime(selectedUser.createdAt) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">最后登录:</span>
                <span class="value">{{ selectedUser.lastLoginTime ? formatDateTime(selectedUser.lastLoginTime) : '从未登录' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">资料更新:</span>
                <span class="value">{{ formatDateTime(selectedUser.updatedAt) }}</span>
              </div>
              <div class="detail-item" v-if="selectedUser.registerIp">
                <span class="label">注册IP:</span>
                <span class="value">{{ selectedUser.registerIp }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 重置密码弹窗 -->
    <div v-if="showPasswordDialog" class="modal-overlay" @click="closePasswordDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>重置密码 - {{ selectedUser?.nickname }}</h3>
          <button class="close-btn" @click="closePasswordDialog">
            <i class="iconify" data-icon="mdi:close"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="resetPassword">
            <div class="form-group">
              <label>新密码 *</label>
              <input 
                v-model="passwordForm.newPassword" 
                type="password" 
                required 
                minlength="6"
                class="form-input"
                placeholder="请输入新密码"
              >
            </div>
            <div class="form-group">
              <label>确认新密码 *</label>
              <input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                required 
                minlength="6"
                class="form-input"
                placeholder="请再次输入新密码"
              >
            </div>
            <div class="form-group">
              <label>操作原因</label>
              <textarea 
                v-model="passwordForm.reason" 
                class="form-textarea"
                placeholder="请说明重置密码的原因..."
                rows="3"
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closePasswordDialog">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                重置密码
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>



    <!-- 批量操作弹窗 -->
    <div v-if="showBatchDialog" class="modal-overlay" @click="closeBatchActionDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>批量操作 ({{ selectedUsers.length }} 个用户)</h3>
          <button class="close-btn" @click="closeBatchActionDialog">
            <i class="iconify" data-icon="mdi:close"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="executeBatchAction">
            <div class="form-group">
              <label>批量操作类型 *</label>
              <select v-model="batchForm.actionType" class="form-select" required>
                <option value="">请选择操作类型</option>
                <option value="ban">批量封禁</option>
                <option value="unban">批量解封</option>
                <option value="activate">批量激活</option>
                <option value="grant_vip">批量赠送VIP</option>
                <option value="revoke_vip">批量取消VIP</option>
                <option value="recharge">批量充值</option>
                <option value="deduct">批量扣费</option>
              </select>
            </div>
            <div class="form-group" v-if="batchForm.actionType === 'ban'">
              <label>封禁天数</label>
              <input 
                v-model.number="batchForm.duration" 
                type="number" 
                min="1"
                class="form-input"
                placeholder="留空为永久封禁"
              >
            </div>
            <div class="form-group" v-if="['recharge', 'deduct'].includes(batchForm.actionType)">
              <label>金额 * (书币)</label>
              <input 
                v-model.number="batchForm.amount" 
                type="number" 
                min="1"
                required 
                class="form-input"
                placeholder="请输入金额"
              >
            </div>
            <div class="form-group" v-if="batchForm.actionType === 'grant_vip'">
              <label>VIP类型 *</label>
              <select v-model="batchForm.vipType" class="form-select" required>
                <option value="">请选择VIP类型</option>
                <option value="monthly">月度VIP</option>
                <option value="yearly">年度VIP</option>
              </select>
            </div>
            <div class="form-group">
              <label>操作原因 *</label>
              <textarea 
                v-model="batchForm.reason" 
                class="form-textarea"
                placeholder="请说明批量操作的原因..."
                rows="3"
                required
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeBatchActionDialog">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                执行批量操作
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

  <!-- 查看密码对话框 -->
  <div v-if="showViewPasswordDialog" class="modal-overlay" @click="closeViewPasswordDialog">
    <div class="modal-dialog" @click.stop>
      <div class="modal-header">
        <h3>查看用户密码</h3>
        <button class="close-btn" @click="closeViewPasswordDialog">
          <i class="iconify" data-icon="mdi:close"></i>
        </button>
      </div>
      <div class="modal-body">
        <div v-if="selectedUser" class="password-info">
          <div class="user-basic-info">
            <h4>{{ selectedUser.nickname }}</h4>
            <p class="user-email">{{ selectedUser.email }}</p>
          </div>
          <div class="password-display">
            <div class="password-field">
              <label>当前密码：</label>
              <div class="password-value">
                <span class="password-text">{{ selectedUser.password}}</span>
                <button 
                  class="copy-btn" 
                  @click="copyPassword"
                  title="复制密码"
                >
                  <i class="iconify" data-icon="mdi:content-copy"></i>
                </button>
              </div>
            </div>
          </div>
          <div class="password-note">
            <i class="iconify" data-icon="mdi:information-outline"></i>
            <span>请妥善保管用户密码信息，避免泄露</span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" @click="closeViewPasswordDialog">
          关闭
        </button>
      </div>
    </div>
  </div>

  <!-- 导入用户数据模态框 -->
  <div v-if="showImportUserDialogState" class="modal-overlay" @click="closeImportUserDialog">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>
          <i class="iconify" data-icon="mdi:upload"></i>
          导入用户数据
        </h3>
        <button class="close-btn" @click="closeImportUserDialog">
          <i class="iconify" data-icon="mdi:close"></i>
        </button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label>选择用户数据文件</label>
          <input 
            type="file" 
            accept=".json,.csv,.xlsx" 
            @change="handleUserFileUpload"
            :disabled="uploading"
            class="file-input"
          >
          <div class="form-hint">
            支持格式：JSON、CSV、Excel (.xlsx)<br>
            文件大小限制：10MB以内<br>
            JSON格式：用户对象数组，包含 email、nickname、password 等字段<br>
            CSV/Excel格式：第一行为标题，包含必需的列名
          </div>
        </div>
        
        <div v-if="uploading" class="upload-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: importProgress + '%' }"></div>
          </div>
          <div class="progress-text">上传进度：{{ importProgress }}%</div>
        </div>
      </div>
    </div>
  </div>



  <!-- 数据加载提示 -->
  <div v-if="loading" class="loading-overlay">
    <div class="loading-spinner">
      <i class="iconify" data-icon="mdi:loading" style="animation: spin 1s linear infinite;"></i>
      <span>加载中...</span>
    </div>
  </div>

  <!-- 错误提示 -->
  <div v-if="errorMessage" class="error-alert">
    <div class="alert-content">
      <i class="iconify" data-icon="mdi:alert-circle"></i>
      <span>{{ errorMessage }}</span>
      <button @click="errorMessage = ''" class="alert-close">
        <i class="iconify" data-icon="mdi:close"></i>
      </button>
    </div>
  </div>

  <!-- 成功提示 -->
  <div v-if="successMessage" class="success-alert">
    <div class="alert-content">
      <i class="iconify" data-icon="mdi:check-circle"></i>
      <span>{{ successMessage }}</span>
      <button @click="successMessage = ''" class="alert-close">
        <i class="iconify" data-icon="mdi:close"></i>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { User } from '@/types'
import { UserManagementDBAPI } from '@/api/userManagementDB'

// 响应式数据
const users = ref<User[]>([])
const loading = ref(false)
const searchQuery = ref('')
const selectedUsers = ref<string[]>([])

// 错误和成功消息
const errorMessage = ref('')
const successMessage = ref('')

// 筛选器
const filters = ref({
  status: '',
  vipStatus: '',
  role: '',
  dateRange: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 统计数据 - 初始化为0，从API获取真实数据
const userStats = ref({
  totalUsers: 0,
  totalUsersGrowth: 0,
  activeUsers: 0,
  activeUsersGrowth: 0,
  vipUsers: 0,
  vipUsersGrowth: 0,
  newUsersToday: 0,
  newUsersTodayGrowth: 0
})

// 弹窗状态
const showUserDialog = ref(false)
const showDetailDialog = ref(false)
const showPasswordDialog = ref(false)
const showViewPasswordDialog = ref(false)

const showBatchDialog = ref(false)
const isEditing = ref(false)
const selectedUser = ref<User | null>(null)

// 表单数据
const userForm = ref({
  email: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  role: 'user' as User['role'],
  status: 'active' as User['status'],
  vipStatus: 'none' as User['vipStatus'],
  level: 1,
  balance: 0,
  avatar: ''
})

const passwordForm = ref({
  newPassword: '',
  confirmPassword: '',
  reason: ''
})



const batchForm = ref({
  actionType: '',
  duration: undefined as number | undefined,
  amount: 0,
  vipType: '' as 'monthly' | 'yearly' | '',
  reason: ''
})

// 计算属性
const filteredUsers = computed(() => {
  let result = users.value

  // 搜索筛选
  if (searchQuery.value) {
    result = result.filter(user => 
      (user.nickname || '').toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      (user.email || '').toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.id.toString().includes(searchQuery.value)
    )
  }

  // 状态筛选
  if (filters.value.status) {
    result = result.filter(user => user.status === filters.value.status)
  }

  // VIP筛选
  if (filters.value.vipStatus) {
    result = result.filter(user => user.vipStatus === filters.value.vipStatus)
  }

  // 角色筛选
  if (filters.value.role) {
    result = result.filter(user => user.role === filters.value.role)
  }

  return result
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

const totalPages = computed(() => 
  Math.ceil(filteredUsers.value.length / pageSize.value)
)

const isAllSelected = computed(() => 
  paginatedUsers.value.length > 0 && selectedUsers.value.length === paginatedUsers.value.length
)

const isPartialSelected = computed(() => 
  selectedUsers.value.length > 0 && selectedUsers.value.length < paginatedUsers.value.length
)

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    console.log('🔄 开始加载用户数据...')
    const result = await UserManagementDBAPI.getAllUsers(currentPage.value, pageSize.value, searchQuery.value)
    console.log('👥 获取到的用户数据:', result)
    users.value = result.users
    console.log('👥 设置后的 users.value:', users.value)
    console.log('👥 users.value 长度:', users.value.length)
    
    // 使用 UserManagementDBAPI 获取统计数据
    const stats = await UserManagementDBAPI.getUserStats()
    console.log('📊 获取到的统计数据:', stats)
    userStats.value = {
      totalUsers: stats.totalUsers || 0,
      totalUsersGrowth: stats.totalUsersGrowth || 0,
      activeUsers: stats.activeUsers || 0,
      activeUsersGrowth: stats.activeUsersGrowth || 0,
      vipUsers: stats.vipUsers || 0,
      vipUsersGrowth: stats.vipUsersGrowth || 0,
      newUsersToday: stats.newUsersToday || 0,
      newUsersTodayGrowth: stats.newUsersTodayGrowth || 0
    }
    console.log('📊 设置后的 userStats.value:', userStats.value)
  } catch (error) {
    console.error('Failed to load users:', error)
    showMessage('加载用户数据失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}



const refreshData = async () => {
  await loadUsers()
  selectedUsers.value = []
}

const resetFilters = () => {
  filters.value = {
    status: '',
    vipStatus: '',
    role: '',
    dateRange: ''
  }
  searchQuery.value = ''
  currentPage.value = 1
  clearAdvancedFilters()
}

const exportUserData = async () => {
  try {
    // 显示选择导出格式的对话框
    const format = await showExportFormatDialog()
    if (!format) return
    
    loading.value = true
    const blob = await UserManagementDBAPI.exportUsers(format as 'csv' | 'excel')
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    
    const fileExtension = format === 'excel' ? 'xlsx' : 'csv'
    a.download = `用户数据导出_${new Date().toISOString().split('T')[0]}.${fileExtension}`
    
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    showMessage(`用户数据导出成功！格式：${format.toUpperCase()}`, 'success')
  } catch (error) {
    console.error('Export error:', error)
    showMessage('导出失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 显示导出格式选择对话框
const showExportFormatDialog = (): Promise<string | null> => {
  return new Promise((resolve) => {
    const format = prompt('请选择导出格式:\n1. CSV格式 (输入: csv)\n2. Excel格式 (输入: excel)\n\n请输入格式:', 'csv')
    if (format && ['csv', 'excel'].includes(format.toLowerCase())) {
      resolve(format.toLowerCase())
    } else if (format === null) {
      resolve(null) // 用户取消
    } else {
      alert('无效的格式，请输入 csv 或 excel')
      resolve(null)
    }
  })
}

// 导入用户数据对话框状态
const showImportUserDialogState = ref(false)
const showImportNovelDialogState = ref(false)
const uploading = ref(false)
const importProgress = ref(0)

// 导入用户数据
const showImportUserDialog = () => {
  showImportUserDialogState.value = true
}

const closeImportUserDialog = () => {
  showImportUserDialogState.value = false
  uploading.value = false
  importProgress.value = 0
}

const handleUserFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 支持多种文件格式
  const allowedExtensions = ['.json', '.csv', '.xlsx']
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
  
  if (!allowedExtensions.includes(fileExtension)) {
    showMessage('请选择支持的文件格式：JSON、CSV 或 Excel (.xlsx)', 'error')
    return
  }

  // 文件大小检查 (限制为10MB)
  if (file.size > 10 * 1024 * 1024) {
    showMessage('文件大小不能超过10MB', 'error')
    return
  }

  uploading.value = true
  importProgress.value = 0

  try {
    const formData = new FormData()
    formData.append('userData', file)
    formData.append('fileType', fileExtension.substring(1))

    // 模拟进度
    const progressInterval = setInterval(() => {
      if (importProgress.value < 90) {
        importProgress.value += 10
      }
    }, 200)

    const response = await fetch('/api/users/import', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: formData
    })

    clearInterval(progressInterval)
    importProgress.value = 100

    const result = await response.json()
    
    if (response.ok) {
      const importedCount = result.data?.importedCount || result.importedCount || 0
      const skippedCount = result.data?.skippedCount || result.skippedCount || 0
      
      let message = `导入成功！成功导入 ${importedCount} 个用户`
      if (skippedCount > 0) {
        message += `，跳过 ${skippedCount} 个重复用户`
      }
      
      showMessage(message, 'success')
      await loadUsers() // 刷新用户列表
      closeImportUserDialog()
    } else {
      showMessage(`导入失败：${result.message || '未知错误'}`, 'error')
    }
  } catch (error) {
    console.error('Import error:', error)
    showMessage('导入失败，请检查文件格式和网络连接', 'error')
  } finally {
    uploading.value = false
    importProgress.value = 0
    // 清空文件输入
    target.value = ''
  }
}

// 导入小说
const showImportNovelDialog = () => {
  showImportNovelDialogState.value = true
}

const closeImportNovelDialog = () => {
  showImportNovelDialogState.value = false
  uploading.value = false
  importProgress.value = 0
}

const novelImportForm = ref({
  title: '',
  author: '',
  description: '',
  category: 'fantasy',
  coverUrl: '',
  freeChapters: 10,
  vipPrice: 50
})

const handleNovelFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 支持多种文本格式
  const allowedExtensions = ['.txt', '.md', '.doc', '.docx']
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
  
  if (!allowedExtensions.includes(fileExtension)) {
    showMessage('请选择支持的文件格式：TXT、MD、DOC 或 DOCX', 'error')
    return
  }

  // 验证必填字段
  if (!novelImportForm.value.title.trim() || !novelImportForm.value.author.trim()) {
    showMessage('请填写小说标题和作者', 'error')
    return
  }

  // 文件大小检查 (限制为50MB)
  if (file.size > 50 * 1024 * 1024) {
    showMessage('文件大小不能超过50MB', 'error')
    return
  }

  uploading.value = true
  importProgress.value = 0

  try {
    const formData = new FormData()
    formData.append('novelFile', file)
    formData.append('title', novelImportForm.value.title.trim())
    formData.append('author', novelImportForm.value.author.trim())
    formData.append('description', novelImportForm.value.description.trim())
    formData.append('category', novelImportForm.value.category)
    formData.append('coverUrl', novelImportForm.value.coverUrl.trim())
    formData.append('freeChapters', novelImportForm.value.freeChapters.toString())
    formData.append('vipPrice', novelImportForm.value.vipPrice.toString())
    formData.append('fileType', fileExtension.substring(1))

    // 模拟进度
    const progressInterval = setInterval(() => {
      if (importProgress.value < 90) {
        importProgress.value += 5
      }
    }, 500)

    const response = await fetch('/api/novels/import', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: formData
    })

    clearInterval(progressInterval)
    importProgress.value = 100

    const result = await response.json()
    
    if (response.ok) {
      const chaptersCount = result.data?.chaptersCount || result.chaptersCount || 0
      showMessage(`小说《${novelImportForm.value.title}》导入成功！共 ${chaptersCount} 章节`, 'success')
      closeImportNovelDialog()
      
      // 重置表单
      resetNovelImportForm()
    } else {
      showMessage(`导入失败：${result.message || '未知错误'}`, 'error')
    }
  } catch (error) {
    console.error('Import error:', error)
    showMessage('导入失败，请检查文件格式和网络连接', 'error')
  } finally {
    uploading.value = false
    importProgress.value = 0
    // 清空文件输入
    target.value = ''
  }
}

// 重置小说导入表单
const resetNovelImportForm = () => {
  novelImportForm.value = {
    title: '',
    author: '',
    description: '',
    category: 'fantasy',
    coverUrl: '',
    freeChapters: 10,
    vipPrice: 50
  }
}

// 选择相关
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedUsers.value = []
  } else {
    selectedUsers.value = paginatedUsers.value.map(user => user.id)
  }
}

// 用户对话框
const showAddUserDialog = () => {
  isEditing.value = false
  resetUserForm()
  showUserDialog.value = true
}

const showEditUserDialog = (user: User) => {
  isEditing.value = true
  selectedUser.value = user
  userForm.value = {
    email: user.email,
    nickname: user.nickname,
    password: '',
    confirmPassword: '',
    role: user.role,
    status: user.status,
    vipStatus: user.vipStatus,
    level: user.level,
    balance: user.balance,
    avatar: user.avatar || ''
  }
  showUserDialog.value = true
}

const closeUserDialog = () => {
  showUserDialog.value = false
  resetUserForm()
  selectedUser.value = null
}

const resetUserForm = () => {
  userForm.value = {
    email: '',
    nickname: '',
    password: '',
    confirmPassword: '',
    role: 'user',
    status: 'active',
    vipStatus: 'none',
    level: 1,
    balance: 0,
    avatar: ''
  }
}

const saveUser = async () => {
  if (!isEditing.value && userForm.value.password !== userForm.value.confirmPassword) {
    showMessage('两次输入的密码不一致！', 'error')
    return
  }

  try {
    if (isEditing.value && selectedUser.value) {
      // 编辑用户
      const success = await UserManagementDBAPI.updateUser(selectedUser.value.id.toString(), {
        nickname: userForm.value.nickname,
        role: userForm.value.role,
        status: userForm.value.status,
        vipStatus: userForm.value.vipStatus,
        level: userForm.value.level,
        balance: userForm.value.balance,
        avatar: userForm.value.avatar || undefined
      })
      
      if (success) {
        showMessage('用户信息更新成功！', 'success')
        await loadUsers()
        closeUserDialog()
      } else {
        showMessage('用户信息更新失败，请重试！', 'error')
      }
    } else {
      // 添加新用户
      const success = await UserManagementDBAPI.createUser({
        email: userForm.value.email,
        nickname: userForm.value.nickname,
        password: userForm.value.password,
        role: userForm.value.role,
        status: userForm.value.status,
        vipStatus: userForm.value.vipStatus,
        level: userForm.value.level,
        balance: userForm.value.balance,
        avatar: userForm.value.avatar || undefined
      })
      
      if (success) {
        showMessage('用户添加成功！', 'success')
        await loadUsers()
        closeUserDialog()
      } else {
        showMessage('用户添加失败，请重试！', 'error')
      }
    }
  } catch (error) {
    console.error('Save user error:', error)
    showMessage('操作失败，请重试！', 'error')
  }
}

// 用户详情对话框
const showUserDetailDialog = (user: User) => {
  selectedUser.value = user
  showDetailDialog.value = true
}

const closeDetailDialog = () => {
  showDetailDialog.value = false
  selectedUser.value = null
}

// 重置密码对话框
const showResetPasswordDialog = (user: User) => {
  selectedUser.value = user
  passwordForm.value = {
    newPassword: '',
    confirmPassword: '',
    reason: ''
  }
  showPasswordDialog.value = true
}

const closePasswordDialog = () => {
  showPasswordDialog.value = false
  selectedUser.value = null
}

// 查看用户密码
const viewUserPassword = (user: User) => {
  selectedUser.value = user
  showViewPasswordDialog.value = true
}

const closeViewPasswordDialog = () => {
  showViewPasswordDialog.value = false
  selectedUser.value = null
}

const copyPassword = () => {
  if (selectedUser.value?.password) {
    navigator.clipboard.writeText(selectedUser.value.password).then(() => {
      alert('密码已复制到剪贴板')
    }).catch(() => {
      alert('复制失败，请手动复制')
    })
  }
}

const resetPassword = async () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    showMessage('两次输入的密码不一致！', 'error')
    return
  }

  if (!selectedUser.value) return

  try {
    const success = await UserManagementDBAPI.updateUser(selectedUser.value.id.toString(), {
      password: passwordForm.value.newPassword
    })

    if (success) {
      showMessage('密码重置成功！', 'success')
      closePasswordDialog()
    } else {
      showMessage('密码重置失败，请重试！', 'error')
    }
  } catch (error) {
    console.error('Reset password error:', error)
    showMessage('密码重置失败，请重试！', 'error')
  }
}



// 批量操作对话框
const showBatchActionDialog = () => {
  batchForm.value = {
    actionType: '',
    duration: undefined,
    amount: 0,
    vipType: '',
    reason: ''
  }
  showBatchDialog.value = true
}

const closeBatchActionDialog = () => {
  showBatchDialog.value = false
}

const executeBatchAction = async () => {
  if (!selectedUsers.value.length) {
    showMessage('请先选择要操作的用户', 'error')
    return
  }

  try {
    const updates: Partial<User> = {}
    
    switch (batchForm.value.actionType) {
      case 'ban':
        updates.status = 'banned'
        break
      case 'unban':
        updates.status = 'active'
        break
      case 'activate':
        updates.status = 'active'
        break
      case 'grant_vip':
        updates.vipStatus = batchForm.value.vipType as 'monthly' | 'yearly'
        break
      case 'revoke_vip':
        updates.vipStatus = 'none'
        break
      // 充值和扣费需要特殊处理
    }

    const success = await UserManagementDBAPI.batchUpdateUsers(selectedUsers.value, updates)
    
    if (success) {
      showMessage(`批量操作完成！处理了 ${selectedUsers.value.length} 个用户`, 'success')
      await loadUsers()
      selectedUsers.value = []
      closeBatchActionDialog()
    } else {
      showMessage('批量操作失败，请重试！', 'error')
    }
  } catch (error) {
    console.error('Batch operation error:', error)
    showMessage('批量操作失败，请重试！', 'error')
  }
}

// 删除用户
const confirmDeleteUser = async (user: User) => {
  if (confirm(`确定要删除用户 "${getUserDisplayName(user)}" 吗？此操作不可恢复！`)) {
    try {
      const success = await UserManagementDBAPI.deleteUser(user.id.toString())
      if (success) {
        showMessage('用户删除成功！', 'success')
        await loadUsers()
      } else {
        showMessage('用户删除失败，请重试！', 'error')
      }
    } catch (error) {
      console.error('Delete user error:', error)
      showMessage('用户删除失败，请重试！', 'error')
    }
  }
}

// 状态更改
const handleStatusChange = async (user: User, event: Event) => {
  const target = event.target as HTMLSelectElement
  const newStatus = target.value as User['status']
  
  if (newStatus && newStatus !== user.status) {
    const action = newStatus === 'banned' ? '封禁' : newStatus === 'suspended' ? '暂停' : '激活'
    
    if (confirm(`确定要${action}用户 "${getUserDisplayName(user)}" 吗？`)) {
      try {
        const success = await UserManagementDBAPI.updateUser(user.id.toString(), { status: newStatus })
        if (success) {
          user.status = newStatus
          showMessage(`用户${action}成功！`, 'success')
        } else {
          showMessage(`用户${action}失败，请重试！`, 'error')
          target.value = user.status || 'active'
        }
      } catch (error) {
        console.error('Status change error:', error)
        showMessage(`用户${action}失败，请重试！`, 'error')
        target.value = user.status || 'active'
      }
    } else {
      target.value = user.status || 'active'
    }
  }
}

// 搜索和筛选方法
const performSearch = async () => {
  currentPage.value = 1
  await loadUsers()
}

const applyFilters = async () => {
  currentPage.value = 1
  await loadUsers()
}

const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

const applyAdvancedSearch = async () => {
  currentPage.value = 1
  showMessage('高级搜索条件已应用', 'success')
  await loadUsers()
}

const clearAdvancedFilters = () => {
  advancedFilters.value = {
    balanceMin: undefined,
    balanceMax: undefined,
    levelMin: undefined,
    levelMax: undefined,
    dateFrom: '',
    dateTo: '',
    hasLoggedIn: ''
  }
}

// 消息提示方法
const showMessage = (message: string, type: 'success' | 'error') => {
  if (type === 'success') {
    successMessage.value = message
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  } else {
    errorMessage.value = message
    setTimeout(() => {
      errorMessage.value = ''
    }, 5000)
  }
}

// 更新钱包余额显示
const getBalanceAmount = (user: User) => {
  const amount = user.balance || user.coins || 0
  return Number(amount).toLocaleString()
}

// 更新用户详情显示方法
const getUserDisplayName = (user: User) => {
  return user.nickname || user.username || user.email || `用户${user.id}`
}

// 工具函数
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    user: '读者',
    admin: '管理员',
    moderator: '版主'
  }
  return roleMap[role] || role
}

const getVipText = (vipStatus: string) => {
  const vipMap: Record<string, string> = {
    monthly: '月度VIP',
    yearly: '年度VIP',
    none: '普通用户'
  }
  return vipMap[vipStatus] || vipStatus
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '正常',
    banned: '封禁',
    suspended: '暂停'
  }
  return statusMap[status] || status
}

// 日期格式化，处理undefined情况
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatTime = (dateString: string | undefined) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const formatDateTime = (dateString: string | undefined) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/default-avatar.svg'
}

// 生命周期
onMounted(async () => {
  await loadUsers()
})

// 高级搜索相关
const showAdvancedSearch = ref(false)
const advancedFilters = ref({
  balanceMin: undefined as number | undefined,
  balanceMax: undefined as number | undefined,
  levelMin: undefined as number | undefined,
  levelMax: undefined as number | undefined,
  dateFrom: '',
  dateTo: '',
  hasLoggedIn: ''
})
</script>

<style scoped>
/* 页面整体样式 */
.user-data-management-page {
  padding: 24px;
  background-color: #f5f7fa;
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.trend-up {
  display: flex;
  align-items: center;
  gap: 2px;
  color: #10b981;
  font-weight: 500;
}

.trend-label {
  color: #64748b;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon-blue {
  background: #dbeafe;
  color: #3b82f6;
}

.stat-icon-green {
  background: #d1fae5;
  color: #10b981;
}

.stat-icon-orange {
  background: #fed7aa;
  color: #f59e0b;
}

.stat-icon-purple {
  background: #e9d5ff;
  color: #8b5cf6;
}

/* 筛选区域 */
.filter-section {
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

/* 新的统一筛选行布局 */
.filter-row-unified {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: end;
  justify-content: flex-start;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  align-items: end;
  justify-content: space-between;
}

.filter-primary {
  display: flex;
  flex-wrap: nowrap;
  gap: 16px;
  align-items: end;
  flex: 1;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 140px;
  flex: 0 1 auto;
}

/* 统一行布局中的筛选组样式 */
.filter-row-unified .filter-group {
  min-width: 120px;
  flex: 0 1 auto;
}

.filter-row-unified .search-group {
  min-width: 200px;
  flex: 0 1 auto;
}

.filter-row-unified .filter-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  flex: 0 0 auto;
}

.filter-group label {
  font-size: 13px;
  color: #475569;
  font-weight: 500;
  letter-spacing: 0.025em;
}

.search-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 280px;
}

.filter-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 高级筛选区域 */
.advanced-filters {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 20px;
  margin-top: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 紧凑版高级筛选 */
.advanced-filters-compact {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 12px;
  margin-top: 6px;
  margin-bottom: 0;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}

.advanced-content-layout {
  display: flex;
  justify-content: space-between;
  align-items: end;
  gap: 16px;
}

.advanced-filters-left {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: end;
  flex: 1;
}

.advanced-group-small {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.advanced-group-small label {
  font-size: 11px;
  color: #475569;
  font-weight: 500;
  letter-spacing: 0.025em;
}

.range-wrapper-small {
  display: flex;
  align-items: center;
  gap: 6px;
  background: #f8fafc;
  padding: 2px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.range-input-small, .date-input-small {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #cbd5e1;
  border-radius: 4px;
  font-size: 12px;
  min-width: 0;
  background: white;
  transition: all 0.2s ease;
}

.range-input-small:focus, .date-input-small:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.range-wrapper-small span {
  color: #64748b;
  font-weight: 500;
  font-size: 11px;
  white-space: nowrap;
}

.filter-select-small {
  padding: 6px 8px;
  border: 1px solid #cbd5e1;
  border-radius: 6px;
  font-size: 12px;
  background: white;
  transition: all 0.2s ease;
  cursor: pointer;
}

.filter-select-small:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.advanced-actions-right {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-shrink: 0;
}

.advanced-title {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
  letter-spacing: 0.025em;
}

.advanced-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.advanced-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.advanced-group label {
  font-size: 13px;
  color: #475569;
  font-weight: 500;
  letter-spacing: 0.025em;
}

.range-wrapper, .date-range-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f8fafc;
  padding: 4px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.range-input, .date-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #cbd5e1;
  border-radius: 6px;
  font-size: 14px;
  min-width: 0;
  background: white;
  transition: all 0.2s ease;
}

.range-input:focus, .date-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.range-separator {
  color: #64748b;
  font-weight: 500;
  font-size: 13px;
  white-space: nowrap;
}

.advanced-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 5px;
  border-top: 1px solid #f1f5f9;
}

.search-input,
.filter-select {
  padding: 10px 14px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  font-size: 14px;
  min-width: 160px;
  background: white;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.search-input {
  min-width: 240px;
}

.search-input:focus,
.filter-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-select {
  cursor: pointer;
}

.filter-select:hover {
  border-color: #94a3b8;
}

/* 表格样式 */
.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/* 设置各列的固定宽度 */
.data-table th:nth-child(1),
.data-table td:nth-child(1) {
  width: 50px; /* 复选框列 */
}

.data-table th:nth-child(2),
.data-table td:nth-child(2) {
  width: 200px; /* 用户信息列 */
}

.data-table th:nth-child(3),
.data-table td:nth-child(3) {
  width: 150px; /* 登录信息列 */
}

.data-table th:nth-child(4),
.data-table td:nth-child(4) {
  width: 120px; /* 账号状态列 */
}

.data-table th:nth-child(5),
.data-table td:nth-child(5) {
  width: 110px; /* VIP状态列 */
}

.data-table th:nth-child(6),
.data-table td:nth-child(6) {
  width: 140px; /* 钱包余额列 */
}

.data-table th:nth-child(7),
.data-table td:nth-child(7) {
  width: 120px; /* 注册时间列 */
}

.data-table th:nth-child(8),
.data-table td:nth-child(8) {
  width: 200px; /* 操作列 */
  min-width: 200px;
}

.data-table th,
.data-table td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.data-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.data-table tbody tr:hover {
  background-color: #f9fafb;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f3f4f6;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.user-email {
  color: #6b7280;
  font-size: 13px;
  margin-bottom: 2px;
}

.user-id,
.user-role {
  color: #9ca3af;
  font-size: 12px;
}

/* 登录信息样式 */
.login-info {
  font-size: 13px;
}

.last-login {
  margin-bottom: 8px;
}

.register-ip {
  color: #6b7280;
}

/* 状态样式 */
.status-cell {
  min-width: 120px;
}

.status-select {
  padding: 4px 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 12px;
  background: white;
}

.status-select.active {
  color: #059669;
  border-color: #059669;
}

.status-select.banned {
  color: #dc2626;
  border-color: #dc2626;
}

.status-select.suspended {
  color: #d97706;
  border-color: #d97706;
}

.ban-reason,
.ban-expire {
  font-size: 11px;
  color: #6b7280;
  margin-top: 4px;
}

/* VIP状态样式 */
.vip-status {
  min-width: 120px;
}

.vip-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background-color: #fef3c7;
  color: #d97706;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.normal-user {
  color: #6b7280;
  font-size: 13px;
}

.vip-expire {
  font-size: 11px;
  color: #6b7280;
  margin-top: 4px;
}

/* 钱包信息样式 */
.wallet-info {
  min-width: 120px;
  max-width: 140px;
  overflow: hidden;
}

.balance-amount {
  font-weight: 600;
  color: #059669;
  margin-bottom: 4px;
  font-size: 13px;
  word-break: break-all;
  line-height: 1.2;
}

.recharge-info {
  color: #6b7280;
  font-size: 10px;
  line-height: 1.3;
}

.recharge-info small {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 日期信息样式 */
.date-info {
  font-size: 13px;
  color: #6b7280;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 3px;
  justify-content: center;
  align-items: center;
  min-height: 50px;
  padding: 4px 2px;
}

.action-row {
  display: flex;
  gap: 4px;
  align-items: center;
  justify-content: center;
}

.action-btn {
  min-width: 52px;
  height: 24px;
  padding: 0 4px;
  border: none;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
  cursor: pointer;
  font-size: 10px;
  transition: all 0.2s;
  white-space: nowrap;
  flex-shrink: 0;
}

.action-btn .iconify {
  font-size: 11px;
  flex-shrink: 0;
}

.action-btn span {
  font-size: 9px;
  font-weight: 500;
  flex-shrink: 0;
}

.btn-placeholder {
  min-width: 52px;
  height: 24px;
}

.action-btn.edit {
  background-color: #dbeafe;
  color: #3b82f6;
}

.action-btn.edit:hover {
  background-color: #3b82f6;
  color: white;
}

.action-btn.detail {
  background-color: #e0f2fe;
  color: #0891b2;
  border: 1px solid #0891b2;
}

.action-btn.detail:hover {
  background-color: #0891b2;
  color: white;
}

.action-btn.password {
  background-color: #fef3c7;
  color: #d97706;
}

.action-btn.password:hover {
  background-color: #d97706;
  color: white;
}



.action-btn.view {
  background-color: #f3f4f6;
  color: #6b7280;
}

.action-btn.view:hover {
  background-color: #6b7280;
  color: white;
}

.action-btn.danger {
  background-color: #fee2e2;
  color: #dc2626;
}

.action-btn.danger:hover {
  background-color: #dc2626;
  color: white;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
}

.pagination-info {
  font-size: 14px;
  color: #6b7280;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  background-color: #f3f4f6;
  border-color: #9ca3af;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  margin: 0 16px;
  font-size: 14px;
  color: #6b7280;
}

/* 按钮样式 */
.btn {
  padding: 10px 18px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 7px;
  transition: all 0.25s ease;
  text-decoration: none;
  letter-spacing: 0.025em;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.btn:hover::before {
  left: 100%;
}

.btn-primary {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border: 1px solid #2563eb;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  transform: translateY(-1px);
}

.btn-success {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: 1px solid #059669;
}

.btn-success:hover {
  background: linear-gradient(135deg, #059669 0%, #047857 100%);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
  transform: translateY(-1px);
}

.btn-warning {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
  border: 1px solid #d97706;
}

.btn-warning:hover {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
  transform: translateY(-1px);
}

.btn-outline {
  background: white;
  color: #64748b;
  border: 1px solid #cbd5e1;
}

.btn-outline:hover {
  background: #f8fafc;
  border-color: #64748b;
  box-shadow: 0 4px 12px rgba(100, 116, 139, 0.15);
  transform: translateY(-1px);
}

/* 小按钮样式 */
.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
  gap: 4px;
}

/* 超小按钮样式 */
.btn-xs {
  padding: 4px 8px;
  font-size: 11px;
  gap: 3px;
  min-width: 50px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

.modal-content.large {
  max-width: 800px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  font-size: 18px;
}

.close-btn:hover {
  background-color: #f3f4f6;
}

.modal-body {
  padding: 20px;
}

/* 表单样式 */
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

/* 用户详情样式 */
.user-detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.detail-section {
  background-color: #f9fafb;
  padding: 16px;
  border-radius: 6px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item .label {
  color: #6b7280;
  font-weight: 500;
  margin-right: 12px;
  min-width: 80px;
}

.detail-item .value {
  color: #1f2937;
  flex: 1;
  text-align: right;
}

.detail-item .value.active {
  color: #059669;
}

.detail-item .value.banned {
  color: #dc2626;
}

.detail-item .value.suspended {
  color: #d97706;
}



.current-balance .amount {
  color: #1e40af;
  font-weight: 700;
  font-size: 18px;
}

/* 查看密码对话框样式 */
.password-info {
  padding: 0;
}

.user-basic-info {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
}

.user-basic-info h4 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.user-email {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.password-display {
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
}

.password-field {
  margin-bottom: 0;
}

.password-field label {
  display: block;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
  font-size: 14px;
}

.password-value {
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: white;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  padding: 12px;
}

.password-text {
  font-family: 'Courier New', monospace;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
  letter-spacing: 1px;
}

.copy-btn {
  padding: 6px 8px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  transition: background-color 0.2s;
}

.copy-btn:hover {
  background-color: #2563eb;
}

.password-note {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 6px;
  padding: 12px;
  color: #92400e;
  font-size: 13px;
}

.password-note .iconify {
  font-size: 16px;
  color: #f59e0b;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .user-detail-grid {
    grid-template-columns: 1fr;
  }
  
  /* 调整操作列宽度 */
  .data-table th:nth-child(8),
  .data-table td:nth-child(8) {
    width: 180px;
    min-width: 180px;
  }
  
  .action-btn {
    min-width: 46px;
    height: 25px;
    padding: 0 3px;
    gap: 2px;
  }
  
  .action-btn span {
    font-size: 8px;
  }
  
  .action-btn .iconify {
    font-size: 10px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .page-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-section {
    padding: 18px;
    margin-bottom: 18px;
  }
  
  .filter-row {
    grid-template-columns: 1fr;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-row-unified {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .advanced-filters-compact {
    padding: 8px;
  }
  
  .advanced-content-layout {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .advanced-filters-left {
    flex-direction: column;
    gap: 8px;
  }
  
  .advanced-actions-right {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .range-wrapper-small {
    flex-direction: column;
    gap: 4px;
    padding: 4px;
  }
  
  .range-wrapper-small span {
    display: none;
  }
  
  .filter-primary {
    grid-template-columns: 1fr;
    gap: 14px;
  }
  
  .filter-group {
    width: 100%;
  }

  .search-group {
    min-width: auto;
    width: 100%;
  }

  .filter-select {
    min-width: auto;
    width: 100%;
  }

  .search-input {
    width: 100%;
    min-width: auto;
  }

  .filter-actions {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  /* 高级筛选移动端样式 */
  .advanced-filters {
    padding: 16px;
  }
  
  .advanced-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .advanced-actions {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  .range-wrapper, .date-range-wrapper {
    flex-direction: column;
    gap: 8px;
    padding: 8px;
  }

  .range-input, .date-input {
    width: 100%;
  }

  .range-separator {
    display: none;
  }

  .btn {
    padding: 8px 14px;
    font-size: 13px;
    min-width: 100px;
  }
  
  /* 更小的屏幕上进一步调整操作按钮 */
  .data-table th:nth-child(8),
  .data-table td:nth-child(8) {
    width: 160px;
    min-width: 160px;
  }
  
  .action-buttons {
    gap: 3px;
  }
  
  .action-btn {
    min-width: 44px;
    height: 23px;
    padding: 0 2px;
  }
  
  .action-btn span {
    font-size: 7px;
  }
  
  .action-btn .iconify {
    font-size: 9px;
  }
  
  .search-input,
  .filter-select {
    min-width: auto;
    width: 100%;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-buttons {
    justify-content: center;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  /* 移动端隐藏文字，只显示图标 */
  .action-btn span {
    display: none;
  }
  
  .action-btn {
    min-width: 32px;
    width: 32px;
    height: 32px;
    padding: 0;
  }
  
  .action-btn .iconify {
    font-size: 16px;
  }
  
  .data-table th:nth-child(8),
  .data-table td:nth-child(8) {
    width: 140px;
    min-width: 140px;
  }
  
  .action-buttons {
    gap: 2px;
  }
}

/* 文件上传和进度条样式 */
.file-input {
  width: 100%;
  padding: 12px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background-color: #f9fafb;
  cursor: pointer;
  transition: border-color 0.2s;
}

.file-input:hover {
  border-color: #3b82f6;
}

.file-input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
  font-style: italic;
}

.upload-progress {
  margin-top: 20px;
  padding: 16px;
  background-color: #f0f9ff;
  border: 1px solid #0ea5e9;
  border-radius: 8px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  color: #1e40af;
}

/* 按钮颜色变体 */
.btn.btn-warning {
  background-color: #f59e0b;
  color: white;
  border: 1px solid #f59e0b;
}

.btn.btn-warning:hover {
  background-color: #d97706;
  border-color: #d97706;
}

.btn.btn-info {
  background-color: #06b6d4;
  color: white;
  border: 1px solid #06b6d4;
}

.btn.btn-info:hover {
  background-color: #0891b2;
  border-color: #0891b2;
}

/* 表单样式增强 */
.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.form-group select,
.form-group input[type="number"] {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-group select:focus,
.form-group input[type="number"]:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-group select:disabled,
.form-group input[type="number"]:disabled {
  background-color: #f9fafb;
  color: #6b7280;
}

/* 高级搜索面板样式 */
.advanced-search-panel {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.advanced-search-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.advanced-search-content h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  display: flex;
  align-items: center;
  gap: 8px;
}

.advanced-filters {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.filter-item label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.range-inputs span {
  color: #6b7280;
  font-weight: 500;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.advanced-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

/* 加载和提示样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.loading-spinner .iconify {
  font-size: 32px;
  color: #3b82f6;
}

.loading-spinner span {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

.error-alert, .success-alert {
  position: fixed;
  top: 20px;
  right: 20px;
  max-width: 400px;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  animation: slideIn 0.3s ease-out;
}

.error-alert {
  background-color: #fef2f2;
  border: 1px solid #fecaca;
  color: #b91c1c;
}

.success-alert {
  background-color: #f0fdf4;
  border: 1px solid #bbf7d0;
  color: #166534;
}

.alert-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.alert-content .iconify {
  font-size: 20px;
  flex-shrink: 0;
}

.alert-close {
  background: none;
  border: none;
  color: inherit;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  margin-left: auto;
  flex-shrink: 0;
}

.alert-close:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计改进 */
@media (max-width: 768px) {
  .advanced-filters {
    grid-template-columns: 1fr;
  }
  
  .range-inputs {
    flex-direction: column;
    align-items: stretch;
  }
  
  .range-inputs span {
    align-self: center;
    margin: 4px 0;
  }
  
  .date-range {
    flex-direction: column;
    align-items: stretch;
  }
  
  .date-range span {
    align-self: center;
    margin: 4px 0;
  }
  
  .advanced-actions {
    flex-direction: column;
  }
}

/* 搜索包装器样式 */
.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: white;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.search-wrapper:focus-within {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-wrapper .search-input {
  border: none;
  border-radius: 0;
  box-shadow: none;
  padding-right: 45px;
}

.search-wrapper .search-input:focus {
  box-shadow: none;
  border: none;
}

.search-btn {
  position: absolute;
  right: 6px;
  top: 50%;
  transform: translateY(-50%);
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border: none;
  color: white;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.search-btn:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
  transform: translateY(-50%) translateY(-1px);
}

.search-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: translateY(-50%);
}
</style> 